package com.group9.handinhand.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.group9.handinhand.service.so.PasswordResetLinkSO;
import com.group9.handinhand.service.so.UserSO;
import com.group9.handinhand.utils.HandInHandSecureRandom;

@Transactional
@Service("mailService")
public class MailServiceImpl implements MailService {
	
	@Autowired
	MailSender mailSender;
	
	@Autowired
	SimpleMailMessage templateMessage;
	
	@Value(value = "${application.url}")
	String appUrl;
	
	@Autowired
	UserService userService;
	/**
	 * Sends the password to user with e-mail or username.
	 * @param emailOrUsername
	 * 
	 */
	@Override
	public String sendForgottenPasswordEmail(String emailOrUsername) {
		
		UserSO user = userService.getUserByEmail(emailOrUsername);
		if(user == null) {
			user = userService.getUserByUsername(emailOrUsername);
		}
		
		if(user != null) {
			
			PasswordResetLinkSO link = userService.savePasswordResetLink(user, new HandInHandSecureRandom().nextRandomPasswordResetLink());
			
			if(link != null) {
				SimpleMailMessage simpleMailMessage = new SimpleMailMessage(this.templateMessage);
				simpleMailMessage.setTo(user.getEmail());
				simpleMailMessage.setText("Dear " + user.getName() + ", \nYou can reset your password from the link below: \n"
						+ appUrl + "/resetPassword/" + link.getLink());
				
		        try{
		            this.mailSender.send(simpleMailMessage);
		            return user.getEmail();
		        }
		        catch (MailException ex) {
		            System.err.println(ex.getMessage());
		        }
			}
		}
		return null;
	}
	
}
